package org.eenie.kdassistant.ui.scan;

import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.os.Vibrator;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.RadioGroup;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.zltd.industry.ScannerManager;

import org.eenie.kdassistant.R;
import org.eenie.kdassistant.net.kdy_api.KdyApi;
import org.eenie.kdassistant.net.xz_api.XingZheApi;
import org.eenie.kdassistant.net.yd_api.YDApi;
import org.eenie.kdassistant.net.zzt_api.ZZTApi;
import org.eenie.kdassistant.ui.BaseActivity;
import org.eenie.kdassistant.ui.ExpressEntity;
import org.eenie.kdassistant.ui.ExpressEntityDao;
import org.eenie.kdassistant.ui.setting.SettingActivity;
import org.eenie.kdassistant.utils.LogUtil;
import org.eenie.kdassistant.utils.RegExpUtil;
import org.eenie.kdassistant.utils.SoundUtils;
import org.eenie.kdassistant.utils.ToastUtils;

import java.util.ArrayList;
import java.util.List;

import cn.bingoogolapple.qrcode.core.QRCodeView;

public class ScanActivity extends BaseActivity implements QRCodeView.Delegate
        , ScannerManager.IScannerStatusListener {


    public static final String BROADCAST_ACTION_EXPRESS_UPDATE = "org.eenie.kdassistant.ui.scan.express.update";


    QRCodeView mScaner;
    ScanResAdapter mScanResAdapter;
    RecyclerView mRvScanRes;
    List<ExpressEntity> mEntities = new ArrayList<>();

    protected SoundUtils mSoundUtils;

    XingZheApi mXingZheApi;

    KdyApi mKdyApi;

    ZZTApi mZZTApi;


    YDApi mYDApi;

    AlertDialog dialog;

    ExpressEntityDao mExpressEntityDao;


    String title;


    RadioGroup rg_express_type;

    int decoderType;


    int express_type = 0;

    protected ScannerManager mScannerManager;

    protected Handler mHandle = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            mSoundUtils.success();
            handleCode(msg.getData().getString("data"), -1);
        }
    };


//    private BroadcastReceiver expressStateReceiver = new BroadcastReceiver() {
//        @Override
//        public void onReceive(Context context, Intent intent) {
//            mEntities.clear();
//            mEntities.addAll(loadAllExpress());
//            mScanResAdapter.notifyDataSetChanged();
//        }
//    };


    @Override
    public int initContentView() {
        return R.layout.activity_scan;
    }

    @Override
    public void initInjector() {
        mXingZheApi = getApplicationComponent().getXzApi();
        mZZTApi = getApplicationComponent().getZZTApi();
        mKdyApi = getApplicationComponent().getKdyApi();
        mYDApi = getApplicationComponent().getYDApi();
        mExpressEntityDao = getApplicationComponent().getDaoSession().getExpressEntityDao();
        express_type = getIntent().getIntExtra("express_type", 0);


    }

    @Override
    public void initUiAndListener() {


        if (express_type == 0) {
            setTitle("签收扫描");
        } else {
            setTitle("到件扫描");
        }


        rg_express_type = (RadioGroup) findViewById(R.id.rg_express_type);

//        IntentFilter intentFilter = new IntentFilter(BROADCAST_ACTION_EXPRESS_UPDATE);
//        registerReceiver(expressStateReceiver, intentFilter);
//        Calendar cal = Calendar.getInstance();
//        cal.set(Calendar.HOUR_OF_DAY, 0);
//        cal.set(Calendar.MINUTE, 1);
//        LogUtil.e(" time = " + cal.getTimeInMillis());
//        LogUtil.e(" time = " + cal.getTime().toString());

        mEntities = loadAllExpress();


        try {
            mScannerManager = ScannerManager.getInstance();
            if (mScannerManager != null) {
                decoderType = mScannerManager.getDecoderType();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }


        mSoundUtils = SoundUtils.getInstance();
        mSoundUtils.init(this);

        initView();


    }

    @Override
    protected boolean isApplyStatusBarTranslucency() {
        return false;
    }

    @Override
    protected boolean isApplyStatusBarColor() {
        return true;
    }

    private void initView() {

        mScaner = (QRCodeView) findViewById(R.id.scaner_zxing);
        mScaner.setDelegate(this);


        mRvScanRes = (RecyclerView) findViewById(R.id.rv_scan_res);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(mContext);
        mRvScanRes.setLayoutManager(linearLayoutManager);
        mRvScanRes.addItemDecoration(new DividerItemDecoration(mRvScanRes.getContext(), linearLayoutManager.getOrientation()));
        mRvScanRes.setAdapter(mScanResAdapter = new ScanResAdapter(mEntities, getApplicationComponent()));

//        mScanResAdapter.openLoadAnimation(BaseQuickAdapter.SCALEIN);
//        mScanResAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
//            @Override
//            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
//
//
//
//
//            }
//        });

        mScanResAdapter.setOnItemLongClickListener(new BaseQuickAdapter.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(BaseQuickAdapter adapter, View view, int position) {
                ExpressEntity entity = (ExpressEntity) adapter.getData().get(position);
//                if (entity.getExpressEntityDao()==null) {
//                    entity.setExpressEntityDao(mExpressEntityDao);
//                }
//                if (entity.getCommonApi()==null) {
//                    CommonApi commonApi = mKdyApi;
//                    switch (entity.getType()) {
//                        case 0:
//                            commonApi = mXingZheApi;
//                            break;
//                        case 1:
//                            commonApi = mZZTApi;
//                            break;
//                        case 2:
//                            commonApi = mKdyApi;
//                            break;
//                    }
//                    entity.setCommonApi(commonApi);
//                }
//                entity.upload(ScanActivity.this);
                return true;
            }
        });
    }


    @Override
    public void onScanQRCodeSuccess(String result) {
        vibrate();
        handleCode(result, -1);
        mScaner.startSpot();
    }

    @Override
    public void onScanQRCodeOpenCameraError() {

    }

    @Override
    protected void onStart() {
        super.onStart();


    }


    public void onResume() {


        super.onResume();
        try {
            if (mScannerManager != null) {
                int res = mScannerManager.connectDecoderSRV();
                mScannerManager.addScannerStatusListener(this);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

//        if(decoderType == Constants.DECODER_ONED_SCAN){
//            if (!mScannerManager.getScannerEnable()) {
//                new AlertDialog.Builder(this)
//                        .setTitle(R.string.action_settings)
//                        .setIcon(android.R.drawable.ic_dialog_info)
//                        .setMessage(R.string.scan_message)
//                        .setPositiveButton(R.string.dialog_ok, new DialogInterface.OnClickListener() {
//                            @Override
//                            public void onClick(DialogInterface paramDialogInterface, int paramInt) {
//                                closeSelf();
//                            }
//                        })
//                        .setCancelable(false)
//                        .show();
//            }
//        }
    }

    @Override
    protected void onStop() {
        super.onStop();

        if (mScaner.getVisibility() == View.VISIBLE) {
            mScaner.stopCamera();
        }
    }


    @Override
    protected void onPause() {
        super.onPause();
        try {
            if (mScannerManager != null) {
                mScannerManager.removeScannerStatusListener(this);
                mScannerManager.disconnectDecoderSRV();
            }

        } catch (Exception e) {
            e.printStackTrace();
        }

        if (mScaner.getVisibility() == View.VISIBLE) {

            mScaner.stopCamera();
        }

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {

        menu.add("手动填写");


        menu.add("摄像头扫描");


        menu.add("失败重传");


//        menu.add("登录设置");

//        PackageManager manager = getPackageManager();
//        Drawable xz_drawable = getResources().getDrawable(R.mipmap.ic_launcher);
//        Drawable zzt_drawable = getResources().getDrawable(R.mipmap.ic_launcher);
//        Drawable st_drawable = getResources().getDrawable(R.mipmap.ic_launcher);
//        try {
//            xz_drawable = manager.getApplicationIcon("com.yto.receivesend");
//            zzt_drawable = manager.getApplicationIcon("com.geenk.zto.sys");
//            st_drawable = manager.getApplicationIcon("com.kuaibao.skuaidi");
//        } catch (PackageManager.NameNotFoundException e) {
//            e.printStackTrace();
//        }
//        menu.add("行者")
//                .setIcon(xz_drawable)
//                .setShowAsActionFlags(MenuItem.SHOW_AS_ACTION_ALWAYS);
//
//        menu.add("中通")
//                .setIcon(zzt_drawable)
//                .setShowAsActionFlags(MenuItem.SHOW_AS_ACTION_ALWAYS);
//
//        menu.add("申通")
//                .setIcon(st_drawable)
//                .setShowAsActionFlags(MenuItem.SHOW_AS_ACTION_ALWAYS);
        return super.onCreateOptionsMenu(menu);
    }


    @Override
    public boolean onOptionsItemSelected(MenuItem item) {


        if (item.getItemId() == android.R.id.home) {
            finish();
            return true;
        }


        if (item.getTitle().equals("失败重传")) {

            reUpload();

        } else if (item.getTitle().equals("摄像头扫描")) {
            item.setTitle("关闭摄像头");
            openCamera();

        } else if (item.getTitle().equals("手动填写")) {
            showInput();
        } else if (item.getTitle().equals("关闭摄像头")) {
            item.setTitle("摄像头扫描");
            closeCamera();

        } else {
            if (item.getTitle().equals("登录设置")) {
                startActivity(new Intent(mContext, SettingActivity.class));
            }
        }
//        if (item.getTitle().equals("行者")) {
//            Intent intent = new Intent();
//            intent.setAction("com.wrbug.xposeddemo.xz");
//            intent.putExtra("method", 0);
//            mContext.sendBroadcast(intent);
//
//        } else if (item.getTitle().equals("中通")) {
//            Intent intent = new Intent();
//            intent.setAction("com.wrbug.xposeddemo.zzt");
//            intent.putExtra("method", 1);
//            mContext.sendBroadcast(intent);
//        } else if (item.getTitle().equals("申通")) {
//            Intent intent = new Intent();
//            intent.setAction("com.wrbug.xposeddemo.st");
//            intent.putExtra("method", 2);
//            mContext.sendBroadcast(intent);
//        }
        return super.onOptionsItemSelected(item);
    }


    private void handleCode(String result, int type) {
        LogUtil.e(result);


        switch (rg_express_type.getCheckedRadioButtonId()) {
            case R.id.ra_auto:
                type = -1;
                break;
            case R.id.ra_yt:
                type = 0;
                break;
            case R.id.ra_zt:
                type = 1;
                break;
            case R.id.ra_st:
                type = 2;
                break;
            case R.id.ra_yd:
                type = 3;
                break;
        }


        if (result.length() > 6 && RegExpUtil.isNum(result)) {
            if (!isExist(result, express_type)) {
                cacheExpress(result, type);
            } else {
                ToastUtils.showShort("单号已存在\n" + result);
            }
        } else {
            ToastUtils.showShort("单号非法\n" + result);
        }
    }


    private void cacheExpress(String num, int type) {
        ExpressEntity entity = new ExpressEntity(num, type, System.currentTimeMillis());
        entity.setExpress_type(express_type);
        mExpressEntityDao.insert(entity);
        mScanResAdapter.addData(0, entity);
        mScanResAdapter.notifyDataSetChanged();

    }

    private List<ExpressEntity> loadAllExpress() {
        return mExpressEntityDao
                .queryBuilder()
                .orderDesc(ExpressEntityDao.Properties._id)
                .where(ExpressEntityDao.Properties.Express_type.eq(express_type))
                .list();
    }


    private boolean isExist(String result, int express_type) {
        return !mExpressEntityDao.queryBuilder()
                .where(ExpressEntityDao.Properties.Express.eq(result), ExpressEntityDao.Properties.Express_type.eq(express_type)).list().isEmpty();
    }

    private void vibrate() {
        Vibrator vibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE);
        vibrator.vibrate(200);
    }


    @Override
    public void onScannerStatusChanage(int i) {

    }

    @Override
    public void onScannerResultChanage(byte[] bytes) {
        String data = new String(bytes);
        Message msg = mHandle.obtainMessage();
        msg.getData().putString("data", data);
        mHandle.sendMessage(msg);
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
//        unregisterReceiver(expressStateReceiver);
    }


    private void showInput() {
        AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
        builder.setTitle("手动输入面单");
        View view = LayoutInflater.from(mContext).inflate(R.layout.view_input_code_layout, null);
        final EditText edit_code = (EditText) view.findViewById(R.id.edit_express);

        view.findViewById(R.id.btn_cancel).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });

        view.findViewById(R.id.btn_enter).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!TextUtils.isEmpty(edit_code.getText().toString())) {

//                    Intent intent = new Intent();
//                    intent.setAction("com.wrbug.xposeddemo.xz");
//                    intent.putExtra("method", 0);
//                    intent.putExtra("express", edit_code.getText().toString());
//                    mContext.sendBroadcast(intent);

                    handleCode(edit_code.getText().toString(), -1);
                }
                dialog.dismiss();
            }
        });

        builder.setView(view);
        dialog = builder.create();
        dialog.show();
    }


    private void reUpload() {
//        for (ExpressEntity entity : mScanResAdapter.getData()) {
//            if (entity.getExpressEntityDao()==null) {
//                entity.setExpressEntityDao(mExpressEntityDao);
//            }
//            if (entity.getCommonApi()==null) {
//                CommonApi commonApi = mKdyApi;
//                switch (entity.getType()) {
//                    case 0:
//                        commonApi = mXingZheApi;
//                        break;
//                    case 1:
//                        commonApi = mZZTApi;
//                        break;
//                    case 2:
//                        commonApi = mKdyApi;
//                        break;
//                }
//                entity.setCommonApi(commonApi);
//            }
//
//
//            if (entity.getState() == 4) {
//                entity.upload(this);
//            }
//        }
    }


    private void openCamera() {
        if (mScaner.getVisibility() != View.VISIBLE) {
            mScaner.setVisibility(View.VISIBLE);


            mScaner.stopCamera();
            mScaner.startSpotAndShowRect();
        }
    }


    private void closeCamera() {
        if (mScaner.getVisibility() != View.GONE) {
            mScaner.setVisibility(View.GONE);
            mScaner.stopCamera();
            mScaner.stopSpot();
        }
    }
}
